﻿using General.Core.Config;
using General.Entities.Models;
using General.Framework;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace General.Mvc.Filters
{
    public class AdminCheckFilter : ActionFilterAttribute
    {
        private readonly IMemoryCache memoryCache;

        public AdminCheckFilter(IMemoryCache memoryCache)
        {
            this.memoryCache = memoryCache;
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //base.OnActionExecuting(filterContext);
            //效验用户是否已经登录
            var adminSession = filterContext.HttpContext.Session.GetString("Admin");
            var Path = filterContext.HttpContext.Request.Path.Value.ToLower();
            if (string.IsNullOrEmpty(adminSession))
            {
                if (Path.StartsWith("/api/admin/"))
                {
                    ContentResult content = new ContentResult() { StatusCode = 200, Content = JsonHelper.Serialize(new AjaxResult() { code= AjaxResultStateEnum.Error,message ="请先登录！" }) };
                    filterContext.Result = content;
                }
                else
                {
                    //filterContext.HttpContext.Response.Redirect("/Admin/Login");
                    RedirectToActionResult content = new RedirectToActionResult("Login", "Admin", null);
                    filterContext.Result = content;
                }
                
            }
            else
            {
                //滑动过期
                filterContext.HttpContext.Session.SetString("Admin", adminSession);

                var roleList = JsonHelper.Deserialize<List<tc_role>>(memoryCache.Get(GobalConfig.SYSTEM_ROLELISTMEMORYKEY_STRING).ToString());
                var authorityList = JsonHelper.Deserialize<List<tc_authority>>(memoryCache.Get(GobalConfig.SYSTEM_MENULISTMEMORYKEY_STRING).ToString());

                var adminModel = JsonHelper.Deserialize<tc_admin>(adminSession);
                var adminRoleId = adminModel.role.Split(",", StringSplitOptions.RemoveEmptyEntries).Select<string, int>(x => Convert.ToInt32(x)).ToList();
                var adminRoleList = roleList.Where(x=> adminRoleId.Contains(x.id)).ToList();
                //如果为管理员所有页面可访问
                if (adminRoleList.Where(x=>x.rolecode == "admin").FirstOrDefault()!=null)
                {
                    return;
                }
                //设置的权限列表
                var adminRolePermissionList = new List<int>();
                
                if (Path.StartsWith("/admin/"))
                {
                    var currentAuthPage = authorityList.Where(x=>x.menuUrl.ToLower() == Path&&x.isMenu==1).FirstOrDefault();
                    if (currentAuthPage==null)
                        return;
                    var permissionResult = adminRoleList.Where(x => x.permission.Split(",", StringSplitOptions.RemoveEmptyEntries).Select<string, int>(x => Convert.ToInt32(x)).ToList().Contains(Convert.ToInt32(currentAuthPage.id))).FirstOrDefault();
                    if (permissionResult == null)
                    {
                        RedirectToActionResult content = new RedirectToActionResult("403", "Error", null);
                        filterContext.Result = content;
                    }
                }
                else if (Path.StartsWith("/api/admin/"))
                {
                    var currentPathController = Path.Replace("/api/admin/","").Split("/",StringSplitOptions.RemoveEmptyEntries)[0];
                    var currentAuthority = authorityList.Where(x => x.authority.ToLower() == currentPathController).FirstOrDefault();
                    if (currentAuthority == null)
                        return;
                    var permissionResult = adminRoleList.Where(x => x.permission.Split(",", StringSplitOptions.RemoveEmptyEntries).Select<string, int>(x => Convert.ToInt32(x)).ToList().Contains(Convert.ToInt32(currentAuthority.id))).FirstOrDefault();
                    if (permissionResult == null)
                    {
                        ContentResult content = new ContentResult() { StatusCode = 200, Content = JsonHelper.Serialize(new AjaxResult() { code = AjaxResultStateEnum.Error, message = "你没有权限访问！" }) };
                        filterContext.Result = content;
                    }
                }
            }
            

            //return;
        }
    }
}
